from BaslerCam.BaslerCam_class import BaslerCam # qdzs
from MVSCam.MVSCam_class import MVSCam
from sengo_common.myMVSCam import MVSCam as SimCam

from camera.mvs_line_camera.MVSCam_class import MVSCam as MVSLineCam
# open() close() getFrame()


class SafeCam:  # 多次取流， 重连
    def __init__(self, cls, ip0=None, triggermode='off', frame_callback=None):
        self.ip0 = None
        self.cam = None
        self.cls = cls  # 相机句柄
        if ip0 is not None:
            self.open(ip0, triggermode, frame_callback)  # 打开相机，

    def open(self, ip0, triggermode='off', frame_callback=None):
        if ip0 is not None:
            self.ip0 = ip0
            self.triggermode = triggermode
            self.frame_callback = frame_callback
            if frame_callback is None:
                self.cam = self.cls(ip0)
            else:
                self.cam = self.cls(ip0, triggermode, frame_callback)
            return 1

        return 0

    def close(self):
        if self.cam is not None:
            self.cam.close()
        return 0

    def getFrame(self):
        im = None
        for i in range(100):
            im = self.cam.getFrame()
            if im is not None:
                return im
        # if random.random()>0.5:
        #    im = None
        if im is None:
            print('SafeCam: cam reopen')
            self.close()
            self.cam = None
            self.open(self.ip0, self.triggermode, self.frame_callback)
            im = self.cam.getFrame()

        return im

class CamFactory: #
    @staticmethod
    def create(class_type, ip='127.0.0.1'):
        if class_type == "basler":
            return SafeCam(BaslerCam, ip)

        elif class_type == "mvs":
            return SafeCam(MVSCam, ip)

        elif class_type == "mvs_line":
            return SafeCam(MVSLineCam, ip) # 线扫相机

        elif class_type == "sim":
            return SafeCam(SimCam, ip) # from get_config import pp, pp存放图片目录
        else:
            raise ValueError("Invalid transport type")
